<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button v-permission="['超级管理员']" type="primary" icon="el-icon-plus" size="mini" @click="formVisible=true">充值额度</el-button>
        <el-button type="primary" size="mini"  @click="dialogVisible = true">申请额度</el-button>
        <el-button type="primary" size="mini" @click="handleDownload">领用账号模板<i class="el-icon-paperclip el-icon--right"></i></el-button>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="代理商" value="1"></el-option>
              <el-option label="套餐" value="2"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok"/>
      </div>
    </div>
    <el-table stripe style="width: 100%"  border fit highlight-current-row ref="tableDataRef" :data="tableData" :key="key">
      <el-table-column v-if="colData[0].istrue" min-width="50" align="center" prop="id" label="ID"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="50" align="center" prop="agentName" label="代理商"></el-table-column>
      <el-table-column v-if="colData[2].istrue" min-width="50" align="center" prop="platter" label="套餐类型"> </el-table-column>
      <el-table-column v-if="colData[3].istrue"  min-width="100" align="center" prop="count" label="学习卡额度">
      </el-table-column>
      <el-table-column v-if="colData[4].istrue" min-width="80" align="center" prop="term" label="学习卡有效期">
      </el-table-column>
      <el-table-column v-if="colData[5].istrue"  min-width="100" align="center"  prop="use_count" label="已领用数">
      </el-table-column>
      <el-table-column v-if="colData[6].istrue"  min-width="100" align="center" prop="residue"  label="剩余额度"></el-table-column>
      <el-table-column v-if="colData[7].istrue" min-width="140" align="center"  label="领用记录">
        <template slot-scope="scope">
          <el-link type="primary" @click="showDetail(scope.row.platter_id)">查看</el-link>
        </template>
      </el-table-column>
      <el-table-column  label="操作" min-width="150" align="center">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" type="primary" @click="openConsume(scope.row)">领用</el-button>
            <el-button v-permission="['超级管理员']" size="mini" type="primary" @click="openEdit(scope.row)">编辑</el-button>
            <el-button v-permission="['超级管理员']" size="mini" @click="delContent(scope.row.id)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :current-page.sync="listQuery.startSize" background @size-change="handleSizeChange"
                     @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]"
                     layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize">
      </el-pagination>
    </div>
    <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText" />

    <el-dialog title="学习卡额度充值" :visible.sync="formVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="40%" @close="addFormclose">
      <el-form :model="addForm"  ref="ruleForm" :rules="rules" class="diolog_adapt" style="width: 600px" >
        <el-form-item label="代理商:" label-width="130px" prop="agent">
          <el-select v-model="addForm.agent" filterable  placeholder="请选择代理商" :disabled="editSubjects">
            <el-option
              v-for="item in agentArr"
              :key="item.id"
              :label="item.username"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="套餐:" label-width="130px" prop="platter">
          <el-select v-model="addForm.platter" filterable placeholder="请选择套餐" :disabled="editSubjects">
            <el-option
              v-for="item in platterArr"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="editSubjects ? '学习卡额度:' : '充值数量:'" label-width="130px" prop="count">
          <el-input v-model="addForm.count" placeholder="请输入充值数量" type="number" min="0"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible = false" size="mini" round>取 消</el-button>
        <el-button v-if="editSubjects" type="primary" @click="editAccountLimit('ruleForm')" size="mini" round>确定</el-button>
        <el-button v-else type="primary" @click="addAccountLimitControl('ruleForm')" size="mini" round>确定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="学习卡账号领用" :visible.sync="consumeFormVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="40%" @close="consumeFormClose">
      <el-form :model="consumeForm"  ref="consumeForm" :rules="consumeRules" class="diolog_adapt" style="width: 600px" >
        <el-form-item label="学习卡套餐:" label-width="130px" prop="platter">
          <el-input v-model="consumeForm.platter"  disabled></el-input>
        </el-form-item>
        <el-form-item label="本次申领数量:" label-width="130px" prop="count">
          <el-input v-model="consumeForm.count" placeholder="请输入申领数量" type="number" min="0"></el-input>
        </el-form-item>
        <el-form-item label="导入文件:" label-width="130px" class="snElsx">
          <div class="">
            <el-input autocomplete="off" placeholder="请点击上传，上传xls或xlsx文件" v-model="consumeForm.file.name"></el-input>
            <upload-excel-component class="flex mrg-top" :before-upload="batchUpload" @submitXlsx="submitXlsx"
                                    :loading="!videoFlag">
              <span>{{videoFlag ? '' : goodsData + '%'}}</span>
            </upload-excel-component>
          </div>
        </el-form-item>
        <div v-if="batchShow">
          <el-form-item label="成功导入:" label-width="130px" style="margin-bottom:0">共{{ this.accountData.success}}条
          </el-form-item>
          <el-form-item label="导入失败:" label-width="130px" style="margin-bottom:0"> 共{{ this.accountData.err}}条
            {{ this.accountData.errorCol.length >= 1 ? `( 位于:第${this.accountData.errorCol.toString()}行 ), 只展示前10行` : ''}}
          </el-form-item>
          <el-form-item label="重复的号码:" label-width="130px" style="margin-bottom:0">共{{this.accountData.repeat.length}}条
            {{ this.accountData.repeat.length >= 1 ? `( 位于:第${this.accountData.repeat.toString()}行 ), 只展示前10行` : ''}}
          </el-form-item>
          <el-form-item label="本次申领记录:" label-width="130px" >
            <el-link type="primary" @click="downLoadExcelUl(accountData.excelUrl)">点击下载</el-link>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary"  @click="consumeFormVisible = false"  size="mini" round>确定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="dialogVisible"  width="30%">
      <span>您好，单独申请学习卡数额，请联系您的业务经理或联系我司4006784158服务热线，目前暂不支持线上单独申请，谢谢！</span>
    </el-dialog>
  </div>
</template>

<script>
  import objectable from "@/utils/objectable.js";
  import dynamicTable from "@/components/DynamicTable/index";
  import deleteDialog from "@/components/deleteDialog/index";
  import tableMini from '@/utils/tableMini.js'
  import {
    editContentClass,
    getPlatter,
    addAccountLimit,
    queryAccountLimit,
    consumeAccount,
    deleteAccountLimit, editAccountLimit
  } from "@/api/launcherMade";
  import {getAgentAndSchool, getAgentUser, getBatchTwo} from "@/api/equipment";
  import {mapState} from "vuex";
  import UploadExcelComponent from "@/components/UploadExcelSn/index.vue";
  import permission from "@/directive/permission";
  import {Loading} from "element-ui";

  export default {
    mixins: [tableMini],
    components: {dynamicTable, deleteDialog, UploadExcelComponent},
    directives: { permission },
    data() {
      return {
        key: 1,
        colData: [], //动态控制table
        checkboxVal: ["ID", "代理商", "套餐类型", "学习卡额度", "学习卡有效期", "已领用数", "剩余额度", "领用记录"],
        searchTable: "",
        select: "", //搜索条件
        tableData: [],
        listQuery: {
          startSize: 1,
          pageSize: 10,
          userId: localStorage.getItem("ID"),
        },
        addForm: {
          agent: '',
          platter: '',
          count: '',
        },
        consumeForm: {
          platter: '',
          count: '',
          file: [],
          id: '',
          platter_id: '',
        },
        formVisible: false,
        rules: {
          agent: [{ required: true, message: '请选择代理商', trigger: 'change' }],
          platter: [{ required: true, message: '请选择可关联文件性质', trigger: 'change' }],
          count: [{required: true, message: '请输入数量', trigger: 'blur'}],
        },
        consumeRules: {
          platter: [{ required: true, message: '请选择代理商', trigger: 'blur' }],
          count: [{required: true, message: '请输入申领数量', trigger: 'blur'}],
          file:  [{required: true, message: '请选择文件', trigger: 'blur'}],
        },
        editSubjects: false,
        deleteDialogs: { show: false, deleteText: '', deleteId: 0 },
        courseTypeOptions: [{label:'视频',value:1},{label: '音频',value: 2}, {label: '文档',value: 3}, {label: '图片', value: 4}],
        childrenOption: [],  //子账号可选框
        batchArr: [],
        platterArr: [],
        agentArr: [],
        dialogVisible: false,
        accountData: {},
        batchShow:false,
        consumeFormVisible: false,
        videoFlag: true,
      }
    },
    created() {
      this.colData = objectable(this.checkboxVal, this.checkboxVal); //转为数组对象，好控制table
      this.getAccountLimit()
      this.getBatchTwo()
      this.getPlatter()
      this.getAgentAndSchool()
    },
    methods: {
      Refresh() {
        this.listQuery = { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), name: undefined}
        this.getAccountLimit()
      },
      getBatchTwo() {
        getBatchTwo({ userId: localStorage.getItem("ID") }).then(res => {
          this.batchArr = res.data
        }).catch(err => {
          this.batchArr = []
        })
      },
      getPlatter() {
        getPlatter({userId: localStorage.getItem("ID")}).then(res => {
          this.platterArr = res.data
        }).catch(err => {
          this.platterArr = []
        })
      },
      getAgentAndSchool() {
        getAgentAndSchool({userId: localStorage.getItem("ID")}).then(res => {
          this.agentArr = res.data
        }).catch(err => {
          this.agentArr = []
        })
      },
      downLoadExcelUl(excelUrl) {
        let loadingInstance = Loading.service({ target: '.content2' })
        window.open('https://' + excelUrl)
        this.$nextTick(() => {
          loadingInstance.close();
        });
      },
      //搜索,1:课程名称
      idnameSearch() {
        if (!this.select) return this.$message.warning("请先选择查询条件");
        this.listQuery.startSize = 1
        this.listQuery.pageSize = 10
        switch (this.select) {
          case '1':
            this.listQuery.agentName = this.searchTable
            this.getAccountLimit();
            break;
          case '2':
            this.listQuery.platter = this.searchTable
            this.getAccountLimit();
            break;
        }
      },
      openEdit(row) {
        this.formVisible = true
        this.editSubjects=true
        this.addForm = {
          agent: row.agent,
          platter: row.platter_id,
          count: row.count,
          id: row.id
        }
      },
      editAccountLimit(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            let editForm = JSON.parse(JSON.stringify(this.addForm))
            editForm.last_ip = sessionStorage.getItem("Ip")
            editForm.userId = localStorage.getItem("ID")
            editAccountLimit(editForm).then(res => {
              this.$message.success(res.msg)
              this.getAccountLimit()
              this.formVisible = false
              this.editSubjects = false
            }).catch(err => {
            })
          } else {
            return false;
          }
        });
      },
      addAccountLimitControl(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            let addForm = JSON.parse(JSON.stringify(this.addForm))
            addForm.last_ip = sessionStorage.getItem("Ip")
            addForm.userId = localStorage.getItem("ID")
            addAccountLimit(addForm).then(res => {
              this.$message.success(res.msg)
              this.getAccountLimit()
              this.formVisible = false
            }).catch(err => {
            })
          } else {
            return false;
          }
        });
      },
      getAccountLimit() {
        queryAccountLimit(this.listQuery).then(res => {
          if(res.code==200){
            this.tableData = res.data
            this.total = res.total
          }else{
            this.$message.error(this.res.msg)
          }
        }).catch(err => {
          this.tableData = []
          this.total = 0
        })
      },
      editContent(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            let editForm = JSON.parse(JSON.stringify(this.addForm))
            editForm.last_ip = sessionStorage.getItem("Ip")
            editForm.userId = localStorage.getItem("ID")
            editContentClass(editForm).then(res => {
              this.$message.success(res.msg)
              this.formVisible = false
              this.getAccountLimit()
            }).catch(err => {
            })
          } else {
            return false;
          }
        });
      },
      delContent(id) {
        this.deleteDialogs.show = true
        this.deleteDialogs.deleteId = id
      },
      showDetail(platter_id) {
        this.$router.push({name:'accountManage', query:{platter_id: platter_id}});
      },
      openConsume(row) {
        this.consumeFormVisible = true
        this.consumeForm = {
          id: row.id,
          platter: row.platter,
          count: '',
          file: [],
          platter_id: row.platter_id
        }
      },
      batchUpload(file) {
        this.consumeForm.file = file
      },
      consumeFormClose() {
        this.$nextTick(() => {
          this.consumeForm = this.$options.data().consumeForm
          this.videoFlag = true
          this.batchShow = false
        })
      },
      submitXlsx(event) {
        var fd = new FormData()
        fd.append('file', this.consumeForm.file)
        fd.append('userId', localStorage.getItem("ID"))
        fd.append('last_ip', sessionStorage.getItem("Ip"))
        fd.append('count', this.consumeForm.count)
        fd.append('id', this.consumeForm.id)
        fd.append('platter_id', this.consumeForm.platter_id)
        this.videoFlag = false
        consumeAccount(fd).then(res => {
          this.accountData = res.data
          this.batchShow = true
          this.$message.success(res.msg)
          this.videoFlag = true
          this.getAccountLimit()
        }).catch(err => {
          this.videoFlag = true
        })
      },

      //领用账号模板
      handleDownload() {
        let tHeader = ["手机账号", "姓名", "性别", "校区", "年级", "班级", "详细地址", "备注"];
        let filterVal = ["phone", "username", "sex", "school", "grade", "class", "address", "remark"];
        let list = [{ "phone": '15992603175', "username": '张三', "sex": "男", "school": "清华大学", "grade": "一年级", "class": "2班", "address": "广东省深圳市龙岗区", "remark": "这是备注"}]
        import("@/vendor/Export2Excel").then(excel => {
          const data = this.formatJson(filterVal, list);
          excel.export_json_to_excel({ header: tHeader, data, filename: '领用账号模板' });
          this.downloadLoading = false;
        });
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v =>
          filterVal.map(j => {
            if (j === "timestamp") {
              return parseTime(v[j]);
            } else {
              return v[j];
            }
          })
        );
      },
      //删除按钮事件
      deleteEvents() {
        let params = {
          userId: localStorage.getItem("ID"),
          last_ip: sessionStorage.getItem("Ip"),
          id: this.deleteDialogs.deleteId,
        }
        deleteAccountLimit(params).then(res => {
          if(res.code==200){
            this.$message.success(res.msg)
          }else{
            this.$message.error(res.msg)
          }
          this.getAccountLimit()
        }).catch(err => {
          console.log("请求失败", err)
        })
      },
      //分页
      handleSizeChange(val) {
        this.listQuery.pageSize = val
        this.getAccountLimit()
      },
      handleCurrentChange(val) {
        this.listQuery.startSize = val
        this.getAccountLimit()
      },
      //下拉动态table子组件
      alterCheckbok(key, conte) {
        this.key = key;
        this.colData.filter(i => {
          if (conte.indexOf(i.title) != -1) {
            i.istrue = false;
            this.$nextTick(() => {
              this.$refs.tableDataRef.doLayout();
            });
          } else {
            i.istrue = true;
            this.$nextTick(() => {
              this.$refs.tableDataRef.doLayout();
            });
          }
        });
      },
      //编辑添加表单关闭事件
      addFormclose() {
        this.editSubjects=false
        this.$nextTick(() => {
          this.addForm = this.$options.data().addForm
        })
      },
    },
    computed: {
      ...mapState({//获取上传滚动条
        goodsData: state => state.user.progress
      })
    },
  }
</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
  }
  .avatar {
    width: 80px;
    height: 80px;
    display: block;
  }
</style>


